package cloud.forms;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cloud.beans.Person;
import cloud.dao.PersonDao;

public final class PersonForm extends Form{

	private static final String CHAMP_FIRSTNAME = "firstName";
	private static final String CHAMP_LASTNAME = "lastName";

	private PersonDao personDao;
	private Person person;
	
	public PersonForm() {
		
		super();
		this.personDao = new PersonDao();
		this.person = new Person();
	}
	
	
	public Person createPerson( HttpServletRequest request ) {
	
		String first_name = getValeurChamp( request, CHAMP_FIRSTNAME );
		String last_name = getValeurChamp( request, CHAMP_LASTNAME );
	
		try {
			validationChampRequis(first_name);
		}
		catch ( Exception e ) {
			setErreur( CHAMP_FIRSTNAME, e.getMessage() );
		}
		this.person.setFirstName( first_name );
		
		try {
			validationChampRequis(last_name);
		}
		catch ( Exception e ) {
			setErreur( CHAMP_LASTNAME, e.getMessage() );
		}
		this.person.setLastName( last_name );
		
			
		if ( this.erreurs.isEmpty() ) {
			if (this.personDao.creer(this.person))
				resultat = "Success.";
			else {
				setErreur(null, "Error.");
				this.resultat = "Technical Error.";
			}
		} 
		else {
			this.resultat = "Error.";
		}

		return this.person;
	}
	
	public List<Person> getList() {
		
		// Récuperation de la liste des codes en fonction de la rubrique
		List<Person> people = personDao.lister();

		// Si la recherche retourne un resultat
		if ( people != null && !people.isEmpty() ) {
			resultat = "Liste récupérée.";
		}
		
		return people;
	}
	
	
	public Person getPersonById( long id ){

		// Récuperation de la liste des codes en fonction de la rubrique
		Person person = personDao.trouver( id );

		// Si la recherche retourne un resultat
		if ( person != null ) {
			resultat = "Entrée récupérée.";
		}
		
		return person;
	}
}